import {getApiJson, invoke} from './base'
import store from '@/store'
const LOGIN_API = 'api/Ecp.OnlineUser.apiLogin'
const sessionStorage = window.sessionStorage
// import { mapGetters, mapActions } from 'vuex'
// import fetch from './base.js'

export function loginByName (loginName, password) {
  const data = {
    loginName,
    password
  }
  return getApiJson('api/Ecp.OnlineUser.apiLogin', data)
}

export function logout () {
  return getApiJson('api/Ecp.OnlineUser.logout')
}

export function refreshAuth () {

}

export const auth = {
  user: {
    authenticated: false
  },

  login (creds) {
    return getApiJson(LOGIN_API, creds)
      .then((res) => {
        if (res) {
          let user = {
            loginName: res.user.loginName,
            avatarId: res.user.avatarId,
            employeeId: res.user.typeInstanceId,
            userId: res.id,
            name: res.user.name,
            token: res.token
          }
          store.dispatch('setUserInfo', user)
          this.user.authenticated = true
          // sessionStorage.setItem('token', res.token);
          sessionStorage.token = res.token
          // sessionStorage.setItem('avatar', res.user.avatarId)
          sessionStorage.user = JSON.stringify(user)
        }
      })
  },

  logout () {
    // TODO confirm
    invoke('api/Ecp.OnlineUser.logout', {})
      .then(() => {
        // sessionStorage.removeItem('token')
        this.user.authenticated = false
        router.push('/login')
      }).catch((e) => {
        // sessionStorage.removeItem('token')
        this.user.authenticated = false
        router.push('/login')
      })
  },

  refreshAuth () {
    // console.log(store.getters.getUserInfo.userId)
    let _token = sessionStorage.getItem('token')
    if (!_.isEmpty(_token)) {
      this.user.authenticated = true
      // debugger
      if (_.isEmpty(store.getters.userInfo.userId)) {
        // console.log(JSON.parse(sessionStorage.user));
        store.dispatch('setUserInfo', JSON.parse(sessionStorage.user || '{}'))
      }
    } else {
      this.user.authenticated = false
    }
  },

  checkAuth () {
    // console.log(this.user.authenticated);
    // console.log(store.getters.getUserInfo.userId)
    return this.user.authenticated
  },

  getAvatar () {
    let avatarUrl = sessionStorage.getItem('avatar')
    // debugger
    return _.isEmpty(avatarUrl) ? '' : avatarUrl
  }
}
